package youxiao.bytezon.enums;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;

import javax.persistence.AttributeConverter;

public class CustomOrdinalEnumConverter<X extends CustomOrdinalEnum> implements AttributeConverter<CustomOrdinalEnum, Integer> {

	private Class<X> xclazz;
	private Method valuesMethod;

	@SuppressWarnings("unchecked")
	public CustomOrdinalEnumConverter() {
		this.xclazz = (Class<X>) (((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments())[0];
		try {
			valuesMethod = xclazz.getMethod("values");
		} catch (Exception e) {
			throw new RuntimeException("can't get values method from " + xclazz);
		}
	}

	@Override
	public Integer convertToDatabaseColumn(CustomOrdinalEnum attribute) {
		return attribute.getValue();
	}

	@Override
	@SuppressWarnings("unchecked")
	public X convertToEntityAttribute(Integer dbData) {
		try {
			X[] values = (X[]) valuesMethod.invoke(null);
			for (X x : values) {
				if (x.getValue().equals(dbData)) {
					return x;
				}
			}
		} catch (Exception e) {
			throw new RuntimeException("can't convertToEntityAttribute" + e.getMessage());
		}
		throw new RuntimeException("unknown dbData " + dbData);
	}

}
